import type { App } from "vue";
import { isEmpty } from "@/utils/common";
import { showLoading, hideLoading } from "@/utils/message";

/**
 * 自定义下载指令
 * @description 使用方式：v-down="[url,name,isLoading]"，如 `<div v-down="['https://www.baidu.com','ceshi.txt',false]"></div>`
 * @description url 下载文件路径 name 下载文件名称 isLoading 是否显示loading
 */
export default (app: App) => {
    app.directive("down", {
        mounted(el, binding) {
            if (isEmpty(binding.value[0])) return false;

            el.addEventListener("click", () => {
                let link = document.createElement("a");
                let url = binding.value[0];
                let fileName = isEmpty(binding.value[1])
                    ? url.substring(url.lastIndexOf("/") + 1)
                    : binding.value[1];
                let isLoading = isEmpty(binding.value[2])
                    ? false
                    : binding.value[2];

                if (isLoading) showLoading("正在下载中...");

                // 这里是将url转成blob地址，
                fetch(url)
                    .then((res) => res.blob())
                    .then((blob) => {
                        if (isLoading) hideLoading();
                        link.style.display = "none";
                        link.href = URL.createObjectURL(blob);
                        link.download = fileName;
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        window.URL.revokeObjectURL(link.href);
                    });
            });
        },
    });
};
